/*
 * sys-copyself.c
 *
 * Copyright(c) 2007-2018 Jianjun Jiang <8192542@qq.com>
 * Official site: http://xboot.org
 * Mobile phone: +86-18665388956
 * QQ: 8192542
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software Foundation,
 * Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include <stdint.h>

extern unsigned char boot_spl_start;
extern unsigned char boot_spl_end;
extern void fel_mode(void);
extern void spl_uart_puts(const char *s);
extern void spl_spi_flash_init(void);
extern void spl_spi_flash_exit(void);
extern void spl_spi_flash_read(int addr, void * buf, int count);

enum {
	BOOT_DEVICE_FEL	= 0,
	BOOT_DEVICE_SPI	= 1,
	BOOT_DEVICE_MMC	= 2,
};

static int get_boot_device(void)
{
	uint32_t * t = (void *)0x00000058;

	if(t[0] == 0x1)
		return BOOT_DEVICE_FEL;
	return BOOT_DEVICE_SPI;
}

void spl_copyself(void)
{
	int d = get_boot_device();
	void * mem;
	uint32_t size;

	if(d == BOOT_DEVICE_FEL)
	{
		spl_uart_puts("Boot from FEL\r\n");
		fel_mode();
	}
	else if(d == BOOT_DEVICE_SPI)
	{
		spl_uart_puts("Boot from SPI Flash ...");
		mem = (void *)&boot_spl_start;
		size = &boot_spl_end - &boot_spl_start;

		spl_spi_flash_init();
		spl_spi_flash_read(0, mem, size);
		spl_spi_flash_exit();

		spl_uart_puts("copyself done\r\n");
	}
	else if(d == BOOT_DEVICE_MMC)
	{
		mem = (void *)&boot_spl_start;
		size = (&boot_spl_end - &boot_spl_start + 512) >> 9;
	}
}

